//
//  CountyPLayersViewController.m
//  KG
//
//  Created by Eugene Braginets on 17.03.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CountyPlayersViewController.h"
#import "AppDelegate.h"
#import "PlayerItem.h"
#import "JSONKit.h"
#import "CellPlayer.h"
#import <QuartzCore/QuartzCore.h>
#import "PlayerInfoViewController.h"
#import "bannerView.h"


@implementation CountyPlayersViewController
@synthesize bannerView;
@synthesize tableView=_tableView;
@synthesize grayActivityIndicator = _grayActivityIndicator;
@synthesize playerCell = _playerCell;
@synthesize bannerViewController=_bannerViewController;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector: @selector(loadData)
                                                     name:kPlayerItem object: nil];	
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}




#pragma mark - View lifecycle

- (void) updateUI {

    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                        initWithTarget:self
                                        selector:@selector(loadImage:) 
                                        object:[kPlayersArray objectAtIndex:0]];
    [queue addOperation:operation]; 
    
    for (DataItem* item in kPlayersArray){
        NSOperationQueue *queue = [NSOperationQueue new];
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                            initWithTarget:self
                                            selector:@selector(loadImage:) 
                                            object:item];
        [queue addOperation:operation]; 
    }
    
    [self.grayActivityIndicator setHidden:YES];
    
    [self.tableView setHidden:NO];
    [self.tableView reloadData];
    
}

- (void) loadData {
    
    if (kPlayersArray)
        [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
   
}

- (void)viewDidLoad
{
    [self.grayActivityIndicator setHidden:NO];
    [self.grayActivityIndicator startAnimating];
    [self loadData];
    [self.tableView setHidden:YES];    
//    UIBarButtonItem *logoutButton = [[UIBarButtonItem alloc] 
//                                     initWithTitle:@"More"                                            
//                                     style:UIBarButtonItemStyleBordered 
//                                     target:self 
//                                     action:@selector(more)];
//    self.navigationItem.rightBarButtonItem = logoutButton;
//    [self.view setBackgroundColor:[UIColor colorWithRed:.3 green:.6 blue:.1 alpha:1]];
    
    bannerView *bannerVC=[[bannerView alloc] init];
    [self.view addSubview:bannerVC.view];
    [bannerVC animate];
    self.bannerViewController=bannerVC;
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void) viewWillAppear:(BOOL)animated {
    self.navigationItem.title=@"County Players";
}

- (void)viewDidUnload
{
    [self setBannerView:nil];
    [self setTableView:nil];
    [self setPlayerCell:nil];
    [self setGrayActivityIndicator:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


#pragma mark - TableView  delegate

// Customize the number of sections in the table view.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 62;    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [kPlayersArray count];
}



// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *MyIdentifier = @"MyIdentifier";
    MyIdentifier = @"tblCellView";
    CellPlayer *cell = (CellPlayer*)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if(cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"playerCellView" owner:self options:nil];
        cell=self.playerCell;
    }
    
    
	cell.playerName.text=[[kPlayersArray objectAtIndex:indexPath.row] name];

    
    
    UIImage* cellImage=[[kPlayersArray objectAtIndex:indexPath.row] image];

    float ratio=1;
    float width=cellImage.size.width;
    float height=cellImage.size.height;
    if (height!=0) {
        ratio=width/height;
    }
    if (height==0 || width==0){
        ratio=1;
    }
    
    UIImageView *imageView = [ [ UIImageView alloc ] initWithFrame:CGRectMake(0.0, 0.0, 80*ratio, 80)];
    imageView.image = cellImage;
    imageView.contentMode=UIViewContentModeScaleAspectFill;

   
    [cell.playerImage addSubview:imageView];
//    [cell.playerImage setImage:cellImage];
    [cell.playerImage setContentMode:UIViewContentModeTop];
//    cell.playerImage=[myAppDelegate roundCorners:cell.playerImage frameSize:CGSizeMake(50,50) radius:9.0 frameBorderThickness:0];
//  
    NSString* nickname=[[kPlayersArray objectAtIndex:indexPath.row] nickname];
    NSString* position=[[kPlayersArray objectAtIndex:indexPath.row] role];
    cell.teamName.text=[NSString stringWithFormat:@"%@ %@",position, nickname];
    
    UIView *bgColorView = [[UIView alloc] init];
    [bgColorView setBackgroundColor:[UIColor colorWithRed:.25 green:.3 blue:.05 alpha:0.7]];

    [cell setSelectedBackgroundView:bgColorView];
    [cell setAccessoryView:[self makeDetailDisclosureButton]];
    
    [cell.playerName setHighlightedTextColor:[UIColor whiteColor]];
    [cell.teamName setHighlightedTextColor:[UIColor whiteColor]];
    
    //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setBackgroundColor:[UIColor clearColor]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog (@"selected row %d", indexPath.row);
    PlayerInfoViewController* viewController=[[PlayerInfoViewController alloc] initWith:[kPlayersArray objectAtIndex:indexPath.row]];
    
    [self loadPlayerItem:[[kPlayersArray objectAtIndex:indexPath.row]itemid]];
    viewController.title=[[kPlayersArray objectAtIndex:indexPath.row]name];
    self.navigationItem.title=@"Back";
    
    [self.navigationController pushViewController:viewController animated:YES];    
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    NSLog (@"selected accessory from row %d", indexPath.row);
    
    PlayerInfoViewController* viewController=[[PlayerInfoViewController alloc] initWith:[kPlayersArray objectAtIndex:indexPath.row]];
    
    [self loadPlayerItem:[[kPlayersArray objectAtIndex:indexPath.row]itemid]];
    viewController.title=[[kPlayersArray objectAtIndex:indexPath.row]name];
    self.navigationItem.title=@"Back";

    [self.navigationController pushViewController:viewController animated:YES];
     
}

//helper for accessoryButtonTapped
- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
    if ( indexPath == nil )
        return;
    [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
   
}


#pragma mark - Custom Methods
- (void) loadPlayerItem: (NSString*) itemid {
    //self.fullNewsDict
    
    //NSLog (@"load news item here");
    
    if ([[myAppDelegate dataArraysStore] objectForKey:[NSString stringWithFormat:@"%@%@",kPlayerItem,itemid]] ) {
        NSLog (@"PlayerItem already loaded: %@",itemid);
        return;
    }
    
    [myAppDelegate getData:[NSString stringWithFormat: @"%@&item=%@",kGetPlayersURL,itemid] andType:[NSString stringWithFormat:@"%@%@",kPlayerItem,itemid]];
}


- (UIButton *) makeDetailDisclosureButton {
    UIButton * button =[UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"rightarrow"] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor clearColor]];
    [button setFrame:CGRectMake(0, 0, 25, 25)];
    
    [button setImage:[UIImage imageNamed:@"rightarrow_pressed"] forState:UIControlStateHighlighted];
    [button setImage:[UIImage imageNamed:@"rightarrow_pressed"] forState:UIControlStateSelected];
    
    
    [button addTarget: self
               action: @selector(accessoryButtonTapped:withEvent:)
     forControlEvents: UIControlEventTouchUpInside];
    
    return ( button );
}

- (void)loadImage:(DataItem *)item {
    
    //    int ind=[index intValue];
    
    if (item.image) {
        NSLog (@"image is already loaded for itemId: %@",item.itemid);
        return;   
    }
    else {
        NSLog (@"loading image for itemId: %@",item.itemid);
    }
    
    NSString *imageAddr=[NSString stringWithString:item.imageAddr];
    
    NSLog (@"ImageUrl: %@", imageAddr);
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageAddr]];
    UIImage* image = [[UIImage alloc] initWithData:imageData];

    [item setImage:image];
//    float width=image.size.width;
//    float height=image.size.height;
//    float ratio=width/height;
//
//    
//    [item setImage:[myAppDelegate scale:image toSize:CGSizeMake(150*ratio, 150)]];
//        
    [self performSelectorOnMainThread:@selector(imageDidLoad:) withObject:item waitUntilDone:NO];
}

- (void) imageDidLoad:(DataItem *)item {
    NSLog (@"image for itemId:%@ is loaded!",item.itemid);
    [self.tableView reloadData];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
